<template>
  <div>
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-position="middle"
             label-width="68px"
             size="small" style="margin-top: 10px; padding-left: 5px"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          class="input-select"
          clearable
          placeholder="输入关键词"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" style="padding-left: 10px; margin-top: 5px">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:edit']"
          :disabled="multiple"
          icon="el-icon-plus"
          plain
          size="mini"
          type="warning"
          @click="handleStockIn"
        >添加到入库
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:edit']"
          :disabled="multiple"
          icon="el-icon-plus"
          plain
          size="mini"
          type="warning"
          @click="handleStockOut"
        >添加到出库
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:edit']"
          :disabled="multiple"
          icon="el-icon-plus"
          plain
          size="mini"
          type="warning"
          @click="handleStockClaim"
        >添加到申领
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:edit']"
          :disabled="multiple"
          icon="el-icon-plus"
          plain
          size="mini"
          type="warning"
          @click="handleStockReturn"
        >添加到归还
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:edit']"
          :disabled="multiple"
          icon="el-icon-plus"
          plain
          size="mini"
          type="warning"
          @click="handleStockDestroy"
        >添加到销毁
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" style="margin-right: 20px" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="sampleList" size="small" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form class="table-expand" inline label-position="left">
            <el-form-item label="采样时间">
              <span>{{ parseTime(props.row.samplingTime, '{y}-{m}-{d}') }}</span>
            </el-form-item>
            <el-form-item label="样本源类型">
              <span>{{ props.row.sampSourceTypeName }}</span>
            </el-form-item>
            <el-form-item label="样本组">
              <span>{{ props.row.sampGroupName }}</span>
            </el-form-item>
            <el-form-item label="样本量">
              <span>{{ props.row.sampQuantity }}</span>
            </el-form-item>
            <el-form-item label="样本单位">
              <span>{{ props.row.sampUnit }}</span>
            </el-form-item>
            <el-form-item label="冻融次数">
              <span>{{ props.row.sampFreezeThawCount }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="样本复份编号" prop="sampBackupCode"/>
      <el-table-column align="center" label="样本类型" prop="sampTypeName"/>
      <el-table-column align="center" label="样本源名称" prop="sampSourceName"/>
      <el-table-column align="center" label="样本位置" prop="sampLocation" width="280"/>
      <el-table-column :formatter="sampStateFormat" align="center" label="样本状态" prop="sampState"/>
      <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-hasPermi="['biobank:sample:edit']" icon="el-icon-shopping-bag-1" size="mini" type="text"
                     @click="handleStockOut(scope.row)"
          >出库
          </el-button>
          <el-button v-hasPermi="['biobank:sample:edit']" icon="el-icon-shopping-bag-2" size="mini" type="text"
                     @click="handleStockClaim(scope.row)"
          >申领
          </el-button>
          <el-button v-hasPermi="['biobank:sample:query']" icon="el-icon-view" size="mini" type="text"
                     @click="handleView(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 样本源信息 对话框 -->
    <el-dialog :visible.sync="open" append-to-body title="样本源信息" width="850px">
      <el-row>
        <el-col :span="12">
          <div>
            <span class="samp-label">样本源编号</span>
            <span class="samp-value">{{ sampSourceInfo.sourceCode }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div>
            <span class="samp-label">样本源类型 </span>
            <span class="samp-value">{{ sampSourceInfo.sourceTypeName }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div>
            <span class="samp-label">样本源名称 </span>
            <span class="samp-value">{{ sampSourceInfo.sourceName }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div>
            <span class="samp-label">样本源描述 </span>
            <span class="samp-value">{{ sampSourceInfo.sourceDesc }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div>
            <span class="samp-label">随访状态 </span>
            <span class="samp-value">{{ followStateFormat(sampSourceInfo) }}</span>
          </div>
        </el-col>
      </el-row>
      <el-collapse v-model="activeNames">
        <el-collapse-item :name="1">
          <el-divider><i class="el-icon-s-promotion"></i></el-divider>
          <div
            v-for="(domain, index) in form.formJson"
            :key="index"
            :label="domain.controlLable"
          >
            <parser ref="formCustom" :form-conf="domain.json"/>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = !open">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看样本复份 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="70%">
      <div class="scrollbar" style="height:600px;">
        <el-scrollbar style="height:100%">
          <el-row>
            <el-col :span="7">
              <div>
                <label class="samp-label">样本复份编号 </label>
                <span class="samp-value">{{ form.sampBackupCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本状态 </span>
                <span class="samp-value">{{ sampStateFormat(form) }}</span>
              </div>
              <div>
                <span class="samp-label">样本量 </span>
                <span class="samp-value">{{ form.sampQuantity }}</span>
              </div>
              <div>
                <span class="samp-label">样本单位 </span>
                <span class="samp-value">{{ form.sampUnit }}</span>
              </div>
              <div>
                <span class="samp-label">格式化位置 </span>
                <span class="samp-value">{{ form.sampLocation }}</span>
              </div>
              <div>
                <span class="samp-label">冻融次数 </span>
                <span class="samp-value">{{ form.sampFreezeThawCount }}</span>
              </div>
              <div>
                <span class="samp-label">采样时间 </span>
                <span class="samp-value">{{ form.samplingTime }}</span>
              </div>
              <div>
                <span class="samp-label">条码/二维码 </span>
                <span class="samp-value">{{ form.qrCode }}</span>
              </div>
              <div>
                <span class="samp-label">贴码管/预置管 </span>
                <span class="samp-value">{{ tubeTypeFormat(form) }}</span>
              </div>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <div>
                <span class="samp-label">样本源编号</span>
                <span class="samp-value">{{ sampSourceInfo.sourceCode }}</span>
              </div>
              <div>
                <span class="samp-label">样本源类型 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceTypeName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源名称 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceName }}</span>
              </div>
              <div>
                <span class="samp-label">样本源描述 </span>
                <span class="samp-value">{{ sampSourceInfo.sourceDesc }}</span>
              </div>
              <div>
                <span class="samp-label">随访状态 </span>
                <span class="samp-value">{{ followStateFormat(sampSourceInfo) }}</span>
              </div>
              <el-collapse v-model="activeNames">
                <el-collapse-item :name="1">
                  <!-- <template slot="title">自定义表单<i class="el-icon-s-promotion"></i></template> -->
                  <el-divider><i class="el-icon-s-promotion"></i></el-divider>
                  <div
                    v-for="(domain, index) in form.formJson"
                    :key="index"
                    :label="domain.controlLable"
                  >
                    <parser ref="formCustom" :form-conf="domain.json"/>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-col>
            <el-col :span="0.5">
              <el-divider direction="vertical"></el-divider>
            </el-col>
            <el-col :span="8">
              <!-- 生命周期 -->
              <el-timeline :reverse="reverse">
                <el-timeline-item
                  v-for="(activity, index) in lifeCycles"
                  :key="index"
                  :timestamp="activity.updateTime"
                >
                  {{ activity.typeName }} - {{ activity.createName }}
                </el-timeline-item>
              </el-timeline>
            </el-col>
          </el-row>
          <el-divider content-position="center">同样本其他复份信息</el-divider>
          <el-table :data="sameSamples" max-height="280" size="small">
            <el-table-column align="center" label="复份编号" prop="sampBackupCode" width="150"/>
            <el-table-column align="center" label="样本位置" prop="sampLocation" width="450"/>
            <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fuzzyQuery } from '@/api/biobank/generalQuery'
import { getSameSamples, getSample, getSampleLifeCycle, getSampSourceInfo, updateSamples } from '@/api/biobank/sample'
import { formJsonShow } from '@/api/tool/form'
import Parser from 'form-gen-parser'

export default {
  name: 'FuzzyQuery',
  components: {
    Parser
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 样本复份 表格数据
      sampleList: [],
      // 选中的样本复份
      selectSamples: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      // 样本状态
      sampStateOptions: [],
      // 样本源信息
      sampSourceInfo: {},
      // 是否显示弹出层
      open: false,
      //自定义表单折叠面板默认展开值
      activeNames: 1,
      // 表单参数
      form: {},
      // 选中数组id
      ids: [],
      // 弹出层标题
      title: '',
      reverse: true,
      // 样本生命周期
      lifeCycles: [],
      // 同样本其他复份
      sameSamples: [],
      // 随访状态
      followStateOptions: [],
      // 冻存管类型
      tubeTypeOptions: []
    }
  },
  created() {
    this.getDicts('sample_state').then(response => {
      this.sampStateOptions = response.data
    })
  },
  methods: {
    // 获取样本列表
    getList() {
      this.loading = true
      fuzzyQuery(this.queryParams).then(response => {
        this.sampleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 样本列表选择事件
    handleSelectionChange(selection) {
      this.selectSamples = selection
      this.multiple = !selection.length
    },
    // 入库
    handleStockIn(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      let res = sampBackups.filter((item) => item.sampState !== this.GLOBAL.SAMPLE.VIRTUAL)
      if (res.length > 0) {
        this.$message.warning('所选项中存在非虚拟状态的样本复份')
        return false
      }
      this.handleUpdateSamples(sampBackups, '是否确认添加选中的样本复份到入库', this.GLOBAL.SAMPLE.TO_IN, '添加成功')
    },
    // 出库
    handleStockOut(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      let res = sampBackups.filter((item) => item.sampState !== this.GLOBAL.SAMPLE.NORMAL)
      if (res.length > 0) {
        this.$message.warning('所选项中存在非正常状态的样本复份')
        return false
      }
      this.handleUpdateSamples(sampBackups, '是否确认添加选中的样本复份到出库', this.GLOBAL.SAMPLE.TO_OUT, '添加成功')
    },
    // 申领
    handleStockClaim(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      let res = sampBackups.filter((item) => item.sampState !== this.GLOBAL.SAMPLE.NORMAL)
      if (res.length > 0) {
        this.$message.warning('所选项中存在非正常状态的样本复份')
        return false
      }
      this.handleUpdateSamples(sampBackups, '是否确认添加选中的样本复份到申领', this.GLOBAL.SAMPLE.TO_CLAIM, '添加成功')
    },
    // 归还
    handleStockReturn(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      let res = sampBackups.filter((item) => item.sampState !== this.GLOBAL.SAMPLE.CLAIM)
      if (res.length > 0) {
        this.$message.warning('所选项中存在非领出状态的样本复份')
        return false
      }
      this.handleUpdateSamples(sampBackups, '是否确认添加选中的样本复份到归还', this.GLOBAL.SAMPLE.TO_RETURN, '添加成功')
    },
    // 销毁
    handleStockDestroy(row) {
      let sampBackups
      if (row.sampBackupId) {
        sampBackups = [row]
      } else {
        sampBackups = this.selectSamples
      }
      let res = sampBackups.filter((item) => item.sampState !== this.GLOBAL.SAMPLE.NORMAL)
      if (res.length > 0) {
        this.$message.warning('所选项中存在非正常状态的样本复份')
        return false
      }
      this.handleUpdateSamples(sampBackups, '是否确认添加选中的样本复份到销毁', this.GLOBAL.SAMPLE.TO_DESTROY, '添加成功')
    },
    // 更改样本复份状态
    handleUpdateSamples(sampBackups, title, type, msg) {
      this.$confirm(title, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sampBackups.forEach(item => {
          item.sampState = type
        })
        return updateSamples(sampBackups)
      }).then(() => {
        this.getList()
        this.msgSuccess(msg)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 样本状态状态字典翻译 */
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    // 表单重置
    reset() {
      this.form = {
        sampBackupId: undefined,
        sampId: undefined,
        sampBackupCode: undefined,
        sampState: undefined,
        sampQuantity: undefined,
        sampUnit: undefined,
        sampleBackupSeq: undefined,
        sampLocation: undefined,
        sampFreezeThawCount: undefined,
        samplingTime: undefined,
        qrCode: undefined,
        tubeType: undefined,
        stockState: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
      this.lifeCycles = []
    },
    // 查看按钮事件
    handleView(row) {
      this.reset()
      this.open = true
      const sampBackupId = row.sampBackupId || this.ids
      this.title = '样本复份详情'
      getSample(sampBackupId).then(response => {
        this.form = response.data
      })
      // 获取样本复份生命周期
      getSampleLifeCycle(sampBackupId).then(response => {
        this.lifeCycles = response.data
      })
      // 获取同样本其他复份信息
      getSameSamples(row).then(response => {
        this.sameSamples = response.data
      })
      // 获取样本源信息及自定义表单
      getSampSourceInfo(row.sampSourceId).then(response => {
        this.sampSourceInfo = response.data
        //渲染自定义表单
        const formKey = this.sampSourceInfo.formKey
        const formData = this.sampSourceInfo.formData
        this.formData = this.formData
        this.showCustomForm(formKey, formData)
      })
    },
    /**动态表单展示 */
    showCustomForm(formKey, formData) {
      if (!formKey || formKey === '') {
        this.$set(this.form, 'formJson', undefined)
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form, 'formJson', formJson)
        this.disableForm(this.form.formJson[0].json)
        if (formData != undefined) {
          this.fillFormData(this.form.formJson[0].json, JSON.parse(formData))
          this.$set(this.form, 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },
    // 设置动态表单禁用状态
    disableForm(form) {
      form.fields.map(item => {
        if (item.__vModel__) {
          item.disabled = true
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              child.disabled = true
            })
            return item
          }
        }
      })
    },
    /** 随访状态字典翻译 */
    followStateFormat(row) {
      return this.selectDictLabel(this.followStateOptions, row.followState)
    },
    /** 冻存管类型字典翻译 */
    tubeTypeFormat(row) {
      return this.selectDictLabel(this.tubeTypeOptions, row.tubeType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</script>

<style scoped>
.table-expand {
  font-size: 0;
  padding-left: 90px;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.el-form-item--small.el-form-item {
  margin-bottom: 5px;
}

.samp-label {
  width: 100px;
  font-weight: 700;
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  display: inline-block;
}

.samp-value {
  font-weight: 100;
  text-align: center;
  vertical-align: middle;
  font-size: 14px;
  line-height: 30px;
  margin-left: 36px;
}

.el-divider--vertical {
  display: inline-block;
  height: 20em;
  border-left: 2px dashed #e8eaec;
  position: relative;
  background: 0 0;
}

/deep/ .el-scrollbar__wrap {
  overflow: scroll;
  width: 110%;
  height: 100%;
}

.el-scrollbar {
  display: flex;
  justify-content: space-around;
  padding: 0 10px;
}

.el-scrollbar__bar.is-horizontal {
  display: none;
}
</style>
